﻿using System;
using System.Runtime.InteropServices;

namespace WebBrowserWaiter
{
    using System.IO;

    public class Win32API
        {
            [DllImport("user32", EntryPoint = "SendMessage")]
            public static extern int SendMessage(int hwnd, int wMsg, int wParam, ref int lParam);

            [DllImport("user32", EntryPoint = "RegisterWindowMessage")]
            public static extern int RegisterWindowMessage(string lpString);

            [DllImport("OLEACC.DLL", EntryPoint = "ObjectFromLresult")]
            public static extern int ObjectFromLresult(
                int lResult,
                ref System.Guid riid,
                int wParam,
                [MarshalAs(UnmanagedType.Interface), System.Runtime.InteropServices.In, System.Runtime.InteropServices.Out]ref System.Object ppvObject
                //注意这个函数ObjectFromLresult的声明
            );

        public mshtml.IHTMLDocument2 GetHtmlDocument(int hwnd)
        {
            System.Object domObject = new System.Object();
            int tempInt = 0;
            System.Guid guidIEDocument2 = new Guid();
            int WM_Html_GETOBJECT = Win32API.RegisterWindowMessage("WM_Html_GETOBJECT");//定义一个新的窗口消息
            int W = Win32API.SendMessage(hwnd, WM_Html_GETOBJECT, 0, ref tempInt);//注:第二个参数是RegisterWindowMessage函数的返回值
            int lreturn = Win32API.ObjectFromLresult(W, ref guidIEDocument2, 0, ref domObject);
            mshtml.IHTMLDocument2 doc = (mshtml.IHTMLDocument2)domObject;
            return doc;
        }
    }
}